package com.jiaok.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.deser.BasicDeserializerFactory;
import com.jiaok.entity.LoginUser;
import com.jiaok.entity.SysPermission;
import com.jiaok.entity.SysUser;
import com.jiaok.entity.SysUserRole;
import com.jiaok.service.ISysPermissionService;
import com.jiaok.service.ISysUserRoleService;
import com.jiaok.service.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jiaok
 * @Date 2023/5/8 13:12
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private ISysPermissionService iSysPermissionService;

    @Resource
    private ISysUserRoleService iSysUserRoleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //传入的是前段输入的用户名
        if (StringUtils.isBlank(username)){
            throw new RuntimeException("用户不能为空");
        }
        // TODO: 2023/5/8 查询用户信息 
//        用户名存在
        SysUser user = iSysUserService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
        if (null == user){
            throw new RuntimeException("用户不存在");
        }

        // TODO: 2023/5/8 查询权限部分
        //用户存在，查询其所拥有的权限
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        //先查询当前用户所拥有的角色
        List<SysUserRole> userRoleList = iSysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("uid", user.getId()));
        if (CollUtil.isNotEmpty(userRoleList)){
            List<String> roleList = userRoleList.stream()
                    .filter(sysUserRole -> sysUserRole.getRid() != null)
                    .map(SysUserRole::getRid).collect(Collectors.toList());
            //当前用户所拥有的角色不为空
            if (CollUtil.isNotEmpty(roleList)){
                //查询当前角色所拥有的所有权限
               List<SysPermission> permissions= iSysPermissionService.bulkSelectPermission(roleList);
               if (CollUtil.isNotEmpty(permissions)){
                   for (SysPermission permission : permissions) {
                       if (permission.getType().equals("0") && permission.getDeletFlag().equals("0")){
                           SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getCode());
                           grantedAuthorities.add(simpleGrantedAuthority);
                       }
                   }
               }
            }
        }
//        user.setGrantedAuthorities(grantedAuthorities);
        return new User(user.getUserName(),user.getPassword(),
                user.getEnabled().equals("1"),//账号是否禁用
                user.getAccountNoExpired().equals("0"),//账号是否过期
                user.getCredentialsNoExpired().equals("1"),//密码是够已经过期
                user.getAccountNoLocked().equals("1"),//账户是否已经锁定
                grantedAuthorities);
    }
}
